package com.mashibing.juc.c_015;

import java.util.concurrent.TimeUnit;

/**
 * synchronized优化，
 * 同步代码块中的语句越少越好
 * @author: Yuanzt
 * @Date: 2021/3/26
 * 细化粗糙锁
 */
public class FineCoarseLock {

    int count = 0;
    //对整个方法加锁
    synchronized void m(){
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        count++;
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    void m2(){

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //只对需要加锁的代码加锁
        synchronized (this){
            count ++;
        }
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
